function r(r) {
  var t = r.length;
  if (t > 0) {
    for (var n = 65535, e = 0; e < t; e++) {
      n ^= r[e];
      for (var o = 0; o < 8; o++) n = 0 != (1 & n) ? n >> 1 ^ 40961 : n >> 1;
    }
    return [255 & n, (65280 & n) >> 8];
  }
  return [0, 0];
}

function t(r) {
  return "[object Array]" === Object.prototype.toString.call(r);
}

function n(n, o) {
  return a(r(t(n) ? n : e(n)), o);
}

function e(r) {
  for (var t = r.split(""), n = [], e = 0, o = t.length; e < o; e++) {
    var u = encodeURI(t[e]);
    if (1 == u.length) n.push(u.charCodeAt());
    else
      for (var i = u.split("%"), s = 1; s < i.length; s++) n.push(parseInt("0x" + i[s]));
  }
  return n;
}

function o(r) {
  for (var t = r.split(""), n = [], e = 0, o = t.length; e < o; e++) {
    var u = t[e].charCodeAt();
    u <= 0 || u >= 127 ? n.push(u.toString(16)) : n.push(t[e]);
  }
  return n;
}

function u(r) {
  for (var t = r.split(""), n = [], e = 0, o = t.length; e < o; e++) {
    var u = t[e].charCodeAt();
    u > 0 && u < 127 && n.push(t[e]);
  }
  return n;
}

function i(r, t) {
  r = (r = t ? u(r).join("") : o(r).join("")).replace(/\s/g, "");
  for (var n = (r += r.length % 2 != 0 ? " " : "").length / 2, e = [], i = 0; i < n; i++) e.push(parseInt(r.substr(2 * i, 2), 16));
  return e;
}

function s(r, t, n) {
  void 0 == n && (n = "0");
  for (var e = 0, o = t - r.length; e < o; e++) r = n + r;
  return r;
}

function a(r, t) {
  void 0 === t && (t = !0);
  var n = r[0],
    e = r[1];
  return s((t ? n + 256 * e : 256 * n + e).toString(16).toUpperCase(), 4, "0");
}

function r(r) {
  var t = r.length;
  if (t > 0) {
    for (var n = 65535, e = 0; e < t; e++) {
      n ^= r[e];
      for (var o = 0; o < 8; o++) n = 0 != (1 & n) ? n >> 1 ^ 40961 : n >> 1;
    }
    return [255 & n, (65280 & n) >> 8];
  }
  return [0, 0];
}

function n(n, o) {
  return a(r(t(n) ? n : e(n)), o);
}

function f(n, e) {
  return a(r(t(n) ? n : i(n)), e);
}

function c(r) {
  return f(r);
}

module.exports = {
  ToCRC16: n,
  ToModbusCRC16: f,
  getCRCCmd: function(r) {
    var t = r;
    return r.toUpperCase().startsWith("0X") ? t = r.substr(4) : r.toUpperCase().startsWith("AA") && (t = r.substr(2)),
      r + c(t);
  }
};